﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EngineOfEvermore.Editor.Common;
using Blue.ResourceManager;
using System.Drawing;
using EngineOfEvermore.Imaging;
using System.IO;

namespace EngineOfEvermore.Editor.ImageMapEditor
{
    public class ImageMapReferenceUpdater : IResourceReferenceUpdater
    {
        List<String> _resourceNames = new List<String>();
        int _currentResource;
        String _oldImageName;
        String _newImageName;

        public string Message
        {
            get { return "Updating ImageMaps"; }
        }

        public HashSet<string> ResourceExtensions
        {
            get { return ImageMapEditor.ValidImageExtension; }
        }

        public int ResourceCount
        {
            get { return _resourceNames.Count; }
        }

        public void Init( string oldResourceName, string newResourceName )
        {
            _resourceNames.Clear();
            _resourceNames.AddRange( ResourceManager.FindResources( "ImageMaps", "ximp" ) );

            StringBuilder builder = new StringBuilder();
            int prefixLength = "ImageMaps\\".Length;
            builder.Append( "ImageMaps\\" );

            for ( int i = 0; i < _resourceNames.Count; ++i )
            {
                builder.Length = prefixLength;
                builder.Append( _resourceNames[i] );
                _resourceNames[i] = builder.ToString();
            }

            _currentResource = 0;
            _oldImageName = oldResourceName;
            _newImageName = newResourceName;
        }

        public string CurrentResourceName
        {
            get 
            {
                if ( _currentResource < _resourceNames.Count )
                {
                    return _resourceNames[_currentResource];
                }
                else
                {
                    return null;
                }
            }
        }

        public void ProcessCurrentResource()
        {
            String imageName;
            Size? size;
            ImageMap.IFrameGenerator frameGenerator;

            String resourceName = _resourceNames[_currentResource];

            using ( Stream s = ResourceManager.OpenStream( resourceName, ResourceOpenMode.Read ) )
            {
                ImageMap.LoadFromXmlStream(
                    s,
                    out frameGenerator,
                    out imageName,
                    out size
                    );
            }

            if ( imageName == _oldImageName )
            {
                ImageMap.SaveAsResource( resourceName, frameGenerator, _newImageName, size );
            }

            ++_currentResource;

            if ( _currentResource >= _resourceNames.Count )
            {
                _resourceNames.Clear();
            }
        }
    }
}
